package com.jinzhi.jzapi.certificate.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.certificate.pojo.ConsultationsVo;
import com.jinzhi.jzweb.dao.ArchivesDao;
import com.jinzhi.jzweb.domain.ArchivesDO;
import com.jinzhi.jzweb.domain.CertificateNewsDO;
import com.jinzhi.jzweb.domain.CertificateProfileDO;
import com.jinzhi.jzweb.domain.ConsultationsDO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.DaysUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/index")
public class ApiIndexController extends BaseController{

    @Autowired
    private DictService dictService;
    @Autowired
    private UserService userService;
    @Autowired
    private ConsultationsService consultationsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private   BookOrderService bookOrderService;
    @Autowired
    private ExaminationBatchService examinationBatchService;

    @Autowired
    private ArchivesDao archivesDao;
    /**
     * localhost:8877//jzApi/index/archivesInsert
     * 简历学校档案信息表
     * @return
     */
    @GetMapping("/archivesInsert")
    public Object archivesInsert()throws Exception{

        List<Map> list=archivesService.sumMoneySchool();

        for(Map li:list){
            Map map1 =new HashMap();
            map1.put("name",li.get("orgName"));
            List list1=  archivesService.listArchives(map1);
            if(list1.size()==0){
                ArchivesDO archivesDO=new ArchivesDO();
                archivesDO.setSchoolName(li.get("orgName").toString());
                archivesDO.setUpdateTime(new Date());
                archivesDO.setDepartment(li.get("region_department").toString());
                archivesDO.setPerson(li.get("regionUserId").toString());
                archivesDO.setProvince(li.get("province").toString());
                archivesDO.setNumber(li.get("mobile").toString());
                //考试学生总人数
                archivesDO.setStudentNum(Integer.valueOf(li.get("stuNum").toString()) );
                //应收款
                archivesDO.setMoney((BigDecimal) li.get("receivables"));
                //支出 返款加上劳务费
                archivesDO.setExpenditure( DaysUtil.ToBigDecimal(li.get("returnMoney")).add(DaysUtil.ToBigDecimal(li.get("laborWage")))  );
                //实际总收款
                archivesDO.setActualMoney((BigDecimal) li.get("received"));
                archivesDO.setReturnMoney(DaysUtil.ToBigDecimal(li.get("returnMoney")));
                //劳务费支出
                archivesDO.setLaborWage(DaysUtil.ToBigDecimal(li.get("laborWage")));
                archivesService.insert(archivesDO);
            }
            //学校名称查询所有订单总金额 其他订单总金额  学生人数  老师人数   业务员姓名  电话   部门  支出

          Map mapSchoot=  bookOrderService.orderSchool(li.get("orgName").toString());
            if(mapSchoot!=null){
              String mapschid=  archivesService.schoolNmae(li.get("orgName").toString());
              if(mapschid!=null){
                  ArchivesDO archivesDO=archivesService.selectById(mapschid);
                  //订单总价格
                  archivesDO.setOrderTotal(   DaysUtil.ToBigDecimal(mapSchoot.get("order_money")));
                  //实际订单收款
                  archivesDO.setOrderTotalMoney(DaysUtil.ToBigDecimal(mapSchoot.get("actual_money")));
                  //负责人
                  Map map=   archivesDao.countTeacher(li.get("orgName").toString());
                  if(map==null){
                      archivesDO.setTeacherNum(0);
                  }else {
                      archivesDO.setTeacherNum(Integer.valueOf(map.get("count").toString()));
                  }
                  archivesService.updateById(archivesDO);
              }
            }
            //其他订单统计
            Map mapSchootnew=   bookOrderService.orderSchoolnew(li.get("orgName").toString());
            if(mapSchootnew!=null){
                String mapschid=  archivesService.schoolNmae(li.get("orgName").toString());
                if(mapschid!=null){
                    ArchivesDO archivesDO=archivesService.selectById(mapschid);
                    //订单总价格
                    archivesDO.setOtherOrderTotal(   DaysUtil.ToBigDecimal(mapSchootnew.get("order_money")));
                    //负责人
                    Map map=   archivesDao.countTeacher(li.get("orgName").toString());
                    if(map==null){
                        archivesDO.setTeacherNum(0);
                    }else {
                        archivesDO.setTeacherNum(Integer.valueOf(map.get("count").toString()));
                    }
                    archivesService.updateById(archivesDO);
                }
            }


        }
        List<Map> listOrg=   archivesService.listOrg();
        for(Map li:listOrg){
            if(li.get("province")!=null){
                Map map1 =new HashMap();
                map1.put("name",li.get("orgName"));
                List list1=  archivesService.listArchives(map1);
                if(list1.size()==0){
                    ArchivesDO archivesDO=new ArchivesDO();
                    archivesDO.setSchoolName(li.get("orgName").toString());
                    archivesDO.setUpdateTime(new Date());

                    archivesDO.setProvince(li.get("province").toString());
                    archivesService.insert(archivesDO);
                }
            }


        }


        return Result.ok();
    }


    /**
     * api小程序端-banner图信息接口--公开方法，不需要登录
     *
     * @Description: 首页banner信息查询
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selBanners")
    @Log("api小程序端-banner图信息接口")
    @ApiOperation(value = "api小程序端-banner图信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selBanners() {
        Map<String, String> map = new HashMap<>();
        map.put("name", "证书小程序banner图");
        map.put("type", "cer_banners");
        List<Map> maps = dictService.selTypeNameVue(map);
        return ApiResult.success(maps);
    }


    /**
     * api小程序端-信息列表接口--公开方法，不需要登录
     *
     * @Description: 证书信息列表查询，参数：页码，显示数，栏目名称（筛选条件）
     * @Param: [current, number, columnName]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selNewsList")
    @Log("api小程序端-信息列表接口")
    @ApiOperation(value = "api小程序端-信息列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selNewsList(String current, String number,String firstColumn,String columnName) {
        Page<ConsultationsVo> page = consultationsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number),firstColumn, columnName);
        return ApiResult.success(page);
    }
    
    /**
     * api小程序端-信息列表接口--公开方法，不需要登录
     *
     * @Description: 证书信息列表查询，参数：页码，显示数，栏目名称（筛选条件）
     * @Param: [current, number, columnName]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selDataList")
    @Log("api小程序端-信息列表接口")
    @ApiOperation(value = "api小程序端-信息列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selDataList(@RequestHeader(value = TOKEN_TAG, required = false) String token,String current, String number,String firstColumn,String columnName) {
    	
    	UserDO user = this.getClientUser(token);
    	if (user == null){
            return ApiResult.invalid();
        }
        Page<ConsultationsVo> page = consultationsService.selectListByUserIdPage(Integer.parseInt(current), Integer.parseInt(number),firstColumn, columnName,user.getId());
        
        return ApiResult.success(page);
    }

    /**
     * api小程序端-信息含有缩略图列表接口--公开方法，不需要登录
     *
     * @Description: 缩略图信息查询，参数：页码，显示数，一级栏目，栏目名称（筛选条件）
     * @Param: [current, number, firstColumn，columnName]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selNewsThumbnailList")
    @Log("信息含有缩略图列表接口")
    @ApiOperation(value = "api小程序端-信息含有缩略图列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selNewsThumbnailList(String current, String number,String firstColumn,String columnName) {
        Page<ConsultationsVo> page = consultationsService.selectThumbnailListPage(Integer.parseInt(current), Integer.parseInt(number),firstColumn, columnName);
        return ApiResult.success(page);
    }

    /**
     * api小程序端-信息详情接口--公开方法，不需要登录
     *
     * @Description: 证书信息详情查询，参数：证书信息id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selNewsDetail")
    @Log("api小程序端-信息详情接口")
    @ApiOperation(value = "api小程序端-信息详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selNewsDetail(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("id");
        }

        Map map = new HashMap();
        ConsultationsDO consultationsDO = consultationsService.selectById(id);
        if (consultationsDO != null) {
            map.put("id", consultationsDO.getId());
            map.put("title", consultationsDO.getTitle());//信息标题
            map.put("files", consultationsDO.getFiles());//附件
            map.put("content", consultationsDO.getContents());//内容
            map.put("createrDate", consultationsDO.getCreaterDate());//发布时间
            map.put("accessNumber", consultationsDO.getAccessNumber());//访问次数
            UserDO userDO = userService.selectById(consultationsDO.getCreaterId());
            if (userDO != null) {
                map.put("createrName", userDO.getUsername());
            } else {
                map.put("createrName", "系统管理员");
            }

            //添加查询次数
            Long queries = consultationsDO.getAccessNumber();
            queries = queries + 1;
            consultationsDO.setAccessNumber(queries);
            consultationsService.updateById(consultationsDO);
        }
        return ApiResult.success(map);
    }


    /**
     * api小程序端-证书列表接口--公开方法，不需要登录
     *
     * @Description: 证书信息列表查询，参数：页码，显示数
     * @Param: [current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selCertificateList")
    @Log("api小程序端-证书列表接口")
    @ApiOperation(value = "api小程序端-证书列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCertificateList(String current, String number) {
        Page<Map<String, Object>> page = certificateNewsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number));
        return ApiResult.success(page);
    }


    /**
     * api小程序端-证书详情接口--公开方法，不需要登录
     *
     * @Description: 查询证书详情信息，参数：x证书id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selCertificateDetail")
    @Log("api小程序端-证书详情接口")
    @ApiOperation(value = "api小程序端-证书详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCertificateDetail(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("id");
        }

        Map map = new HashMap();
        CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(id);
        if (certificateNewsDO != null) {
            map.put("id", certificateNewsDO.getId());
            map.put("grade", certificateNewsDO.getGrade());//证书等级
            map.put("relatedMajors", certificateNewsDO.getRelatedMajors());//相关专业
            map.put("examFee", certificateNewsDO.getExamFee());//考试总费用
            map.put("createrDate", certificateNewsDO.getCreaterDate());//发布时间
            map.put("introduce", certificateNewsDO.getIntroduce());//介绍
            CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(certificateNewsDO.getProfileId());
            if (certificateProfileDO != null) {
                map.put("name", certificateProfileDO.getName());//证书名称
                map.put("organization", certificateProfileDO.getOrganization());//发证机构
            } else {
                map.put("name", "");//证书名称
                map.put("organization", "");//发证机构
            }
        }
        return ApiResult.success(map);
    }
}
